//
//  CHSheetSearchView.swift
//  CHSimpleUI
//
//  Created by cyptt on 2023/4/20.
//

import UIKit

//
//  CHBottomSelectView.swift
//  jyzx
//
//  Created by cyptt on 2022/5/11.
//

import UIKit


public class CHSheetSearchView: CHKeyBoardView,UITableViewDelegate,UITableViewDataSource {
    private let mwindow:UIWindow = UIApplication.shared.keyWindow!
    var chaImage:UIImage?
    
    private struct myui{
        static var top_h:CGFloat = 120
        static var bottom_h:CGFloat = 60
        static let title_h:CGFloat = 60
        static let search_h:CGFloat = 60
        
    }
    private let marginL_R = 20   //距离左右边距
    private let marginL_32 = 32 //距离左边
    private let margin_B = 24    //按钮距离底部边距
    private let DefaultH = 190  //只有按钮 + 标题高度
    private let ITEM_H:CGFloat = 44
    private var maxItem = 8   //默认最多显示8行
    
    private var content_H:CGFloat = 190
    private var tableview_H:CGFloat = 44
    
    private var contentPosition:CH_SHEET_LOCAL_TYPE = .bottom
    
    private var searchPlaceholder:String = "请输入"  //是否显示搜索view
    
    private var mShowMaxRow:Int = 8
    private let sureBlueColor:UIColor = UIColor.init(red: 56/255.0, green: 119/255.0, blue: 244/255.0, alpha: 1)
    
    private let CHBottomSelectCellID = "CHBottomSelectCellID"
    private let CHBottomSelectOtherCellID = "CHBottomSelectOtherCellID"
    private var clickKeyBordSearchCallback:((_ text:String) -> ())?
    var dataSourceArr:[CHSheetModel] = []
    var originDataSourceArr:[CHSheetModel] = [] //最原始数据
    
    var selectClosureB:(( _ model:CHSheetModel?) ->Void)?
    var cancelClosureB:(( _ msg:String) ->Void)?
    override init(frame:CGRect){
        super.init(frame: frame)
        print(frame)
        if frame == CGRect.zero {
            print("进来了")
            self.frame = mwindow.bounds
        
        }else{
         
        }
        
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3)
        
        self.addSubview(self.contentV)
        self.addSubview(self.bottomSafeView)
    
    
     
        
    }
    
    deinit{
        print("CHSheetSearchView---deinit")
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /*
     选择了
     */
    public  func setSureCallBack(closure:@escaping(_ model:CHSheetModel?)-> Void)
    {
        
        self.selectClosureB = closure
    }
    
    /*
     取消
     */
    public   func setCancleCallBack(cancelClosure:((_ msg:String)-> Void)?){
        
        self.cancelClosureB = cancelClosure
        
    }
    /*
     view加载到window 上面
     @param showMaxRow 显示最大的行数，默认是8行
     @param isShowSearch 是否显示搜索
     */
    public func show(title:String?,contentTitles:[CHSheetModel]?,showMaxRow:Int = 8,position:CH_SHEET_LOCAL_TYPE = .bottom,placeholder:String = "请输入",controller:UIViewController? = nil){
        weak var weakSelf = self
        dataSourceArr = contentTitles!
        self.originDataSourceArr = dataSourceArr
        self.maxItem = showMaxRow
        self.contentPosition = position
        self.searchPlaceholder = placeholder
        
        self.titleL.text = title
        
        //MARK: - 搜索
        self.searchView.searchTextF.placeholder = placeholder
        self.searchView.setClickKeyBordSearchCallback { searchText in
            print(searchText)
            if weakSelf?.clickKeyBordSearchCallback != nil{
                weakSelf?.clickKeyBordSearchCallback!(searchText)
            }
            weakSelf?.dataSourceArr.removeAll()
            for sheetModel in weakSelf!.originDataSourceArr{
                if sheetModel.titleName!.contains(searchText){
                   
                    weakSelf?.dataSourceArr.append(sheetModel)
                }
            }
            if searchText == ""{
                weakSelf?.dataSourceArr = weakSelf?.originDataSourceArr ?? []
            }
            
            weakSelf?.tableView.reloadData()
        }
        
       
        //MARK: - 搜索end
     
       
        if contentTitles!.count  > maxItem{
            content_H = CGFloat(maxItem) * ITEM_H + myui.top_h + myui.bottom_h
            tableview_H = ITEM_H * CGFloat(maxItem)
        }else{
            content_H = CGFloat(contentTitles!.count) * CGFloat(ITEM_H) + myui.top_h + myui.bottom_h
            tableview_H = CGFloat(contentTitles!.count) * CGFloat(ITEM_H)
        }
     
       
        let corner: UIRectCorner = [.topLeft, .topRight]
        
        if position == .bottom{
            cornerRadiusView(view: contentV, radius: 10, rect: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: content_H), corner: corner)
        }else{
            self.contentV.layer.cornerRadius = 10
            self.contentV.layer.masksToBounds = true
        }
    
      
        self.setPosition()
        if controller != nil{
//            controller?.view.addSubview(self)
            mwindow.addSubview(self)
        }else{
            mwindow.addSubview(self)
        }
  
        
        
        
    }
    
    public func setClickKeyBordSearchCallback(closure:@escaping(_ text:String)-> ()){
        
        self.clickKeyBordSearchCallback = closure
    }
    
    /*
     设置关闭按钮图片
     */
   public func setChaImage(image:UIImage?){
        self.chaImage = image
        self.chaBtn.setImage(image ?? UIImage.init(named: ""), for: UIControl.State.normal)
      
    }
    
    /*
     设置title 位置
     */
    public func setTitlePosition(position:CH_COMMON_SHEET_LOCAL_TYPE){
        
        if position == .center {
            
            self.titleL.textAlignment = .center
            self.titleL.snp.makeConstraints { make in
                make.top.equalTo(self.contentV).offset(20)
                make.centerX.equalTo(self.contentV.snp.centerX)
    
            }
        }else if position == .right{
            self.titleL.textAlignment = .right
            self.titleL.snp.makeConstraints { make in
                make.top.equalTo(self.contentV).offset(20)
                make.right.equalTo(self.chaBtn.snp.left).offset(-5)
    
            }
        }
    }
    
    /*
     取消按钮位置
     */
    public func setCancelPosition(position:CH_COMMON_SHEET_LOCAL_TYPE){
        
        if position == .center {
            
            self.cancelBtn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.center
        }else if position == .right{
            self.cancelBtn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
        }
      
    }
    
    /*
     设置title 字体颜色
     */
    public func setTitleColor(color:UIColor){
        self.titleL.textColor = color
    }
    
    /*
     设置字体
     */
    public func setTitleFont(font:UIFont){
        self.titleL.font = font
    }
    
    /*
     设置取消字体颜色
     */
    public func setCancelTitleColor(color:UIColor){
        self.cancelBtn.setTitleColor(color, for: .normal)
    }
    
    /*
     设置取消字体
     */
    public func setCancelFont(font:UIFont){
        self.cancelBtn.titleLabel?.font = font
    }
    func setPosition(){
        
        if self.contentPosition == .bottom{
            self.contentV.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(self.safeAreaLayoutGuide).offset(0)
                } else {
                    make.bottom.equalTo(self)
                    // Fallback on earlier versions
                }
                make.height.equalTo(content_H)
            }
            self.bottomSafeView.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.top.equalTo(self.contentV.snp.bottom)
                make.bottom.equalTo(self)
            }
            self.cancelBtn.snp.makeConstraints { make in
                make.left.equalTo(self.contentV).offset(marginL_32)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(self.safeAreaLayoutGuide)
                } else {
                    make.bottom.equalTo(self)
                }
                make.right.equalTo(self.contentV).offset(-marginL_32)
                make.height.equalTo(44)
            }
        }else{
            self.contentV.snp.makeConstraints { make in
                make.left.equalTo(marginL_R)
                make.right.equalTo(-marginL_R)
                make.center.equalToSuperview()
                make.height.equalTo(content_H)
            }
            
            self.cancelBtn.snp.makeConstraints { make in
                make.left.equalTo(self.contentV).offset(marginL_32)
                make.bottom.equalTo(self.contentV.snp.bottom).offset(-5)
                make.right.equalTo(self.contentV).offset(-marginL_32)
                make.height.equalTo(44)
            }
        }
       
        
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(self.contentV).offset(marginL_R)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.top.equalTo(self.contentV).offset(myui.top_h)
            make.height.equalTo(tableview_H)
        }
      
        self.searchViewContentView.snp.makeConstraints { make in
            make.left.equalTo(self.contentV).offset(marginL_R)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.top.equalTo(self.contentV).offset(myui.title_h)
            make.height.equalTo(myui.search_h)
        }
        
        
        self.searchView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(40)
            make.width.equalToSuperview()
        }
        self.titleL.snp.makeConstraints { make in
            make.top.equalTo(self.contentV).offset(20)
            make.left.equalTo(self.contentV).offset(marginL_R)

        }
        self.chaBtn.snp.makeConstraints { make in
            make.centerY.equalTo(self.titleL)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.width.height.equalTo(20)
        }
        
      
        
       
     
    }
    
    
    lazy var titleL = {()-> UILabel in
    
        let label:UILabel = UILabel()
        label.text = "标题"
        label.font = UIFont.systemFont(ofSize: 17,weight: UIFont.Weight.bold)
        label.textColor = UIColor.init(red: 35/255.0, green: 41/255.0, blue: 51/255.0, alpha: 1)
   
        return label
    }()
    
    lazy var chaBtn = {()-> UIButton in
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setImage(self.chaImage ??  UIImage.init(named: "gray_cha_icon", in: CHBundle.bundle(), compatibleWith: nil), for: UIControl.State.normal)

        btn.addTarget(self, action: #selector(chaBtnClick(btn:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    lazy var contentV = {()-> UIView in
    
        let contentV:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Int(self.frame.size.width) , height: DefaultH))
     
   
//        contentV.layer.masksToBounds = true
//        contentV.layer.cornerRadius = 10
        contentV.backgroundColor = UIColor.white
        contentV.addSubview(self.titleL)
        contentV.addSubview(self.chaBtn)
    
        contentV.addSubview(self.searchViewContentView)
    
        contentV.addSubview(self.tableView)
        
        contentV.addSubview(self.cancelBtn)
        return contentV
    }()
    
    lazy var bottomSafeView =  {()-> UIView in
        let view:UIView = UIView.init()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    lazy var cancelBtn = {()->UIButton in
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setTitle("取消", for:  UIControl.State.normal)
        btn.setTitleColor(sureBlueColor, for: UIControl.State.normal)
   
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
    
        btn.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
        btn.addTarget(self, action: #selector(cancenBtn(btn:)), for: UIControl.Event.touchUpInside)
     
        return btn
    }()
    
    //MARK: - lazy
    lazy var tableView = {()-> UITableView in
        let tabV = UITableView.init();
        tabV.delegate = self;
        tabV.dataSource = self;
        tabV.backgroundColor = UIColor.clear
        tabV.separatorColor = UIColor.clear
        tabV.showsVerticalScrollIndicator = false
        tabV.showsHorizontalScrollIndicator = false
   
//        tabV.tableHeaderView = self.headerView
//
//        tabV.register(MyCertListCell.self, forCellReuseIdentifier: MyCertListCellID)
      
        return tabV;
    }()
    
    lazy  var searchViewContentView = {()-> UIView in
        let view = UIView.init()
        view.backgroundColor = UIColor.clear
        view.addSubview(self.searchView)
        
        return view
    }()
    
   public lazy var searchView = {()-> CHSearchView in
       let view = CHSearchView.init(style: CHSearchStyle.left)
//       view.searchTextF.placeholder = self.searchPlaceholder
       view.searchTextF.setDefaultPlaceholderColor(placeText: self.searchPlaceholder)
       view.backgroundColor = UIColor.init(red: 247/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1)
       view.searchTextF.textColor = UIColor.init(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1)
       view.layer.cornerRadius = 20
       view.layer.masksToBounds = true
        return view
    }()
}
//btnclick
extension CHSheetSearchView {
    @objc func chaBtnClick(btn:UIButton){
        self.removeFromSuperview()
        if self.cancelClosureB != nil{
            self.cancelClosureB!("取消了")
        }
    }
    
    /*
     按钮点击事件
     */
    @objc func btnClick(btn:UIButton){
       

      
   
    }
    
    @objc func cancenBtn(btn:UIButton){
        self.removeFromSuperview()
        if self.cancelClosureB != nil{
            self.cancelClosureB!("取消了")
        }
    }
}

extension CHSheetSearchView{
   
     func cornerRadiusView(view:UIView,radius:CGFloat,rect:CGRect,corner:UIRectCorner){
       // 圆角大小
//        let radius: CGFloat = 16;
       // 圆角位置
//        let corner: UIRectCorner = [.topLeft, .bottomLeft]
       //frame可以先计算完成  避免圆角拉伸
//        let rect = CGRect(x: 0, y: 0, width: 84, height: 32)
       let path: UIBezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: corner, cornerRadii: CGSize(width: radius, height: radius))
       let maskLayer: CAShapeLayer = CAShapeLayer()
       maskLayer.frame = rect;
       maskLayer.path = path.cgPath
       view.layer.mask = maskLayer;
   }
}

public extension CHSheetSearchView{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataSourceArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model:CHSheetModel = self.dataSourceArr[indexPath.row] as! CHSheetModel
       
        var cell:CHSheetCell? = tableView.dequeueReusableCell(withIdentifier: CHBottomSelectCellID) as? CHSheetCell
        if cell == nil {

            cell = CHSheetCell.init(style: .default, reuseIdentifier:CHBottomSelectCellID )
        }
        cell?.setBottomSelectMolde(model: model)
    
        return cell!
      
    
      
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let model:CHSheetModel = self.dataSourceArr[indexPath.row] as! CHSheetModel
       
      
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.removeFromSuperview()
            if self.selectClosureB != nil{
                self.selectClosureB!(model)
            }
        }
      
    }
}

